//
//  SQLiteDataBaseManager.m
//  Homework_18
//
//  Created by 徐昊 on 16/8/8.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "SQLiteDataBaseManager.h"
#import "Contact.h"
@implementation SQLiteDataBaseManager
/** 
 * 单例创建方式, 只有一个对象
 * 内存管理中, 单例不能被释放
 */
+ (SQLiteDataBaseManager *)shareManager {
    static SQLiteDataBaseManager *manager = nil;
    // 保证安全只执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        manager = [[SQLiteDataBaseManager alloc] init];
    });
    return manager;
}
- (BOOL)isOperationResult:(int)result alertText:(NSString *)text {
    
    BOOL isOperation = YES;
    if (result == SQLITE_OK) {
        
        NSLog(@"%@成功", text);
        isOperation = YES;
    } else {
        
        NSLog(@"%@失败---%d",text, result);
        isOperation = NO;
    }
    return isOperation;
}
/** 打开数据库 */
- (BOOL)openSQLite3 {
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [pathArray firstObject];
    /** 数据库SQLite3文件类型 .db */
    NSString *dbPath = [documents stringByAppendingPathComponent:@"student.db"];
    NSLog(@"%@", dbPath);
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    return  [self isOperationResult:result alertText:@"打开数据库"];
}
/** 关闭数据库 */
- (BOOL)closeSQLite3 {
    int result = sqlite3_close(dbPoint);
    return [self isOperationResult:result alertText:@"关闭数据库"];
}
/** 创建表 */
- (BOOL)createTable {
    NSString *createSQLite = @"create table contact(contact_name text primary key, contact_phoneNumber text, contact_photo text)";
    int result = sqlite3_exec(dbPoint, [createSQLite UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"创建表"];
}
/** 插入数据 */
- (BOOL)insertContact:(Contact *)contact {
    NSString *insertSQLite = [NSString stringWithFormat:@"insert into contact(contact_name, contact_phoneNumber) values ('%@', '%@')", contact.name, contact.phoneNumber];
    int result = sqlite3_exec(dbPoint, [insertSQLite UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"插入数据"];
}
@end
